package com.quan.system.web.controller;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.quan.common.base.bean.PageBean;
import com.quan.common.base.bean.ResultBean;
import com.quan.common.base.enums.CRUD;
import com.quan.common.biz.support.BaseController;
import com.quan.system.entity.SystemPermission;
import com.quan.system.service.SystemPermissionService;

/**
 * <p>
 * 通用用户权限系统-菜单权限表 前端控制器
 * </p>
 *
 * @author 杨浩泉
 * @since 2018-07-05
 */
@RestController
@RequestMapping("/system/permission")
public class SystemPermissionController extends BaseController {

    @Autowired 
    private SystemPermissionService service;

	/**
     * 添加
     * @param  entity 实体
     * @return ResultBean
     */
    @PostMapping("/add")
    public Object add(@Valid @RequestBody SystemPermission entity, BindingResult bindingResult) {
    	if (bindingResult.hasErrors()) {
			return ResultBean.warning(bindingResult.getFieldError().getRejectedValue().toString());
		}
		SystemPermission insertSelective = this.service.insertSelective(entity);
		if (null != insertSelective) {
			return ResultBean.ok();
		} else {
			return ResultBean.failure();
		}
    }

    /**
     * 删除
     * @param id ID
     * @return ResultBean
     */
    @DeleteMapping("/delete/{id}")
    public Object delete(@PathVariable Long id) {
    	int count = this.service.deleteById(id);
    	if(count > 0) {
    		return ResultBean.ok();
    	} else {
    		return ResultBean.failure("通过ID删除失败：[ " + id + " ]");
    	}
    }
    
    /**
     * 批量删除
     * @param params idList(JSON):["1","2"]
     * @return ResultBean
     */
    @PostMapping("/delete")
    public Object delete(@RequestBody Map<String, Object> params) {
    	if(null != params && !params.isEmpty()) {
    		List<Long> idList = JSON.parseArray(params.get("idList").toString(), Long.class);
    		int count = this.service.deleteByIds(StringUtils.join(idList, ","));
        	if(count > 0) {
        		return ResultBean.ok();
        	} else {
        		return ResultBean.failure("通过ID删除失败：[ " + idList + " ]");
        	}
    	}
    	return ResultBean.failure("请选项需要删除的记录");
    }

    /**
     * 修改
     * @param  entity 实体
     * @return ResultBean
     */
    @PostMapping("/update")
    public Object update(@Valid @RequestBody SystemPermission entity, BindingResult bindingResult) {
    	if (bindingResult.hasErrors()) {
            return ResultBean.warning(bindingResult.getFieldError().getDefaultMessage().toString()) ;
        }
    	int count = this.service.updateSelective(entity);
    	if(count > 0) {
    		return ResultBean.ok();
    	} else {
    		return ResultBean.failure();
    	}
    }

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return SystemPermission
    */
    @GetMapping("/get/{id}")
    public Object get(@PathVariable Long id) {
    	SystemPermission entity = this.service.selectOneById(id);
    	if(null != entity) {
    		return ResultBean.ok(entity);
    	} else {
    		return ResultBean.failure("通过ID查询失败：[ " + id + " ]");
    	}
    }
    
    /**
    * 多条件查询数据列表
    *
    * @param entiy 实体对象（查询条件）
    * @return 分页对象
    */
    @GetMapping(value = "/list")
    public Object list(SystemPermission entity) {
		return ResultBean.ok(this.service.selectAll(entity));
    }

    /**
    * 多条件查询分页数据
    *
    * @param entiy 实体对象（查询条件）
    * @return 分页对象
    */
    @GetMapping(value = "/page")
    public Object page(SystemPermission entity) {
		return ResultBean.ok(this.service.selectPage(entity, new PageBean(request)));
    }
    
    /**
     * 根据菜单ID查询权限
     * @param menuId
     * @return
     */
    @GetMapping(value = "/findPermissionByMenuId/{menuId}")
    public Object findPermissionByMenuId(@PathVariable Long menuId) {
		return ResultBean.ok(this.service.findPermissionByMenuId(menuId));
    }
    
    /**
     * 生成菜单默认权限
     * @param params {"menuId": 1, "prefix": "upms:permission", "permissions": ["ui,add,delete,update,page"]}
     * @return
     */
    @PostMapping(value = "/generateDefaultPermission")
    public Object generateDefaultPermission(@RequestBody Map<String, Object> params) {
    	Long menuId = (Long) params.get("menuId");
    	String prefix = (String) params.get("prefix");
    	JSONArray parseArray = JSON.parseArray(params.get("permissions").toString());
    	List<String> permissions = parseArray.toJavaList(String.class) ;
    	
    	if(null == menuId) {
    		return ResultBean.warning("未选择所属菜单") ;
    	}
    	if(StringUtils.isBlank(prefix)) {
    		return ResultBean.warning("请设置权限前缀") ;
    	}
    	if(null == permissions || permissions.isEmpty()) {
    		return ResultBean.warning("请设置需要生成的默认权限") ;
    	}
    	
    	for(int i=0; i<permissions.size(); i++) {
    		SystemPermission entity = new SystemPermission() ;
    		entity.setMenuId(menuId);
    		entity.setSort(100 + (i+1));
    		if(permissions.get(i).equalsIgnoreCase(CRUD.UI.getEnName())) {
    			entity.setName(CRUD.UI.getZhName());
    			entity.setPermission(prefix + ":" + CRUD.UI.getEnName());
    			entity.setType("1");
    		} else if(permissions.get(i).equalsIgnoreCase(CRUD.ADD.getEnName())) {
    			entity.setName(CRUD.ADD.getZhName());
    			entity.setPermission(prefix + ":" + CRUD.ADD.getEnName());
    			entity.setType("2");
    		} else if(permissions.get(i).equalsIgnoreCase(CRUD.DELETE.getEnName())) {
    			entity.setName(CRUD.DELETE.getZhName());
    			entity.setPermission(prefix + ":" + CRUD.DELETE.getEnName());
    			entity.setType("2");
    		} else if(permissions.get(i).equalsIgnoreCase(CRUD.UPDATE.getEnName())) {
    			entity.setName(CRUD.UPDATE.getZhName());
    			entity.setPermission(prefix + ":" + CRUD.UPDATE.getEnName());
    			entity.setType("2");
    		} else if(permissions.get(i).equalsIgnoreCase(CRUD.LIST.getEnName())) {
    			entity.setName(CRUD.LIST.getZhName());
    			entity.setPermission(prefix + ":" + CRUD.LIST.getEnName());
    			entity.setType("2");
    		} else {
    			entity.setName(CRUD.UNKNOWN.getZhName());
    			entity.setPermission(prefix + ":" + CRUD.UNKNOWN.getEnName());
    			entity.setType("2");
    		}
    		
    		this.service.insertSelective(entity) ;
    	}
    	
    	
		return ResultBean.ok();
    }

}
